//
//  ViewController.m
//  19_CarHomeWork
//
//  Created by dllo on 16/8/9.
//  Copyright © 2016年 DM.C. All rights reserved.
//

#import "ViewController.h"
#import "AllCars.h"
#import "Result.h"
#import "Brandlist.h"
#import "List.h"
#import "UIImageView+DownloadImage.h"
#import "AllCarsTableViewCell.h"
#import "HotBrandTableViewCell.h"
#import "ExtensionTableViewCell.h"
#import "ChoseCarTableViewCell.h"
#import "TitleTableViewCell.h"
#import "HotBrand.h"
#import "HotList.h"
#import "HotResult.h"
#import "HeadView.h"
#import "Extension.h"

#define kAllCarsTableViewCell @"allCarsReuse"
#define kHotTableViewCell @"HotReuse"
#define kExtensionTableViewCell @"ExtensionReuse"
#define kChoseTableViewCell @"ChoseReuse"
#define kTitleTableViewCell @"TitleReuse"
@interface ViewController ()<UITableViewDelegate, UITableViewDataSource>
@property (strong, nonatomic) IBOutlet UITableView *tableView;

@property (weak, nonatomic) IBOutlet HeadView *headView;
@property (weak, nonatomic) IBOutlet UICollectionView *hotCollectionView;
@property (nonatomic, strong) AllCars *allCars;
@property (nonatomic, strong) HotBrand *brand;
@property (nonatomic, strong) Extension *extension;
@end

@implementation ViewController

- (void)viewDidLoad {
    [super viewDidLoad];
//    [self allCarsHandleData];
//    [self hotBrandHandleData];
    [self requsetURL:@"http://cars.app.autohome.com.cn/dealer_v6.0.0/dealer/hotbrands-pm1.json"];
    [self requsetURL:@"http://adnewnc.app.autohome.com.cn/autov5.7.0/ad/infoad.ashx?appid=2&platform=1&version=6.2.0&networkid=0&adtype=1&provinceid=110000&lng=121.550888&lat=38.889660&pageindex=1&deviceid=d1ecb940123d620cb05a1b2b0a00da8bdd5e4fbe&idfa=981CD0F4-F1F0-4D0F-9C5E-58280F40E4B0&devicebrand=apple&devicemodel=iPhone&gps_city=210200&pageid=d1ecb940123d620cb05a1b2b0a00da8bdd5e4fbe1470913307169&isretry=0"];
    [self requsetURL:@"http://app.api.autohome.com.cn/autov4.6/cars/brands-a2-pm2-v4.6.1-ts635580073583652962.html"];
    // 添加头视图View
    self.tableView.backgroundColor = [UIColor whiteColor];
    
}
#pragma mark - 处理数据
- (void)allCarsHandleData {
    NSURLSession *URLSession = [NSURLSession sharedSession];
    NSURL *imageURL = [NSURL URLWithString:@"http://app.api.autohome.com.cn/autov4.6/cars/brands-a2-pm2-v4.6.1-ts635580073583652962.html"];
    NSMutableURLRequest *imageURLRequest = [NSMutableURLRequest requestWithURL:imageURL];
    imageURLRequest.HTTPMethod = @"GET";
    NSURLSessionDataTask *dataTask = [URLSession dataTaskWithRequest:imageURLRequest completionHandler:^(NSData * _Nullable data, NSURLResponse * _Nullable response, NSError * _Nullable error) {
        //主线程
        dispatch_async(dispatch_get_main_queue(), ^{
            NSError *error = nil;
            NSDictionary *allCarsDic = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingMutableContainers error:&error];
            self.allCars = [AllCars modelWithDic:allCarsDic];
            [self.tableView reloadData];
        });
    }];
    // 调用这个方法执行
    [dataTask resume];

//    
//    NSString *allCarsJSON = [[NSBundle mainBundle] pathForResource:@"AllCar" ofType:@"json"];
//    NSData *allCarsData = [NSData dataWithContentsOfFile:allCarsJSON];
//    NSError *error = nil;
//    NSDictionary *allCarsDic = [NSJSONSerialization JSONObjectWithData:allCarsData options:NSJSONReadingMutableContainers error:&error];
//    self.allCars = [AllCars modelWithDic:allCarsDic];
}
- (void)hotBrandHandleData {
    
    NSString *hotBrandJSON = [[NSBundle mainBundle] pathForResource:@"HotBrand" ofType:@"json"];
    NSData *hotBrandData = [NSData dataWithContentsOfFile:hotBrandJSON];
    NSError *error = nil;
    NSDictionary *hotBrandDic = [NSJSONSerialization JSONObjectWithData:hotBrandData options:NSJSONReadingMutableContainers error:&error];
    // hotBrand
    _brand = [HotBrand modelWithDic:hotBrandDic];
}
- (void)handleData {
    NSString *path = [[NSBundle mainBundle] pathForResource:@"Extension" ofType:@"json"];
    NSData *pathData = [NSData dataWithContentsOfFile:path];
    NSError *error = nil;
    NSDictionary *extensionCarsDic = [NSJSONSerialization JSONObjectWithData:pathData options:NSJSONReadingMutableContainers error:&error];
    self.extension = [Extension modelWithDic:extensionCarsDic];
    
}
- (void)requsetURL:(NSString *)URL {
    NSURLSession *URLSession = [NSURLSession sharedSession];
    NSURL *imageURL = [NSURL URLWithString:URL];
    NSMutableURLRequest *imageURLRequest = [NSMutableURLRequest requestWithURL:imageURL];
    imageURLRequest.HTTPMethod = @"GET";
       NSURLSessionDataTask *dataTask = [URLSession dataTaskWithRequest:imageURLRequest completionHandler:^(NSData * _Nullable data, NSURLResponse * _Nullable response, NSError * _Nullable error) {
       //主线程
           dispatch_async(dispatch_get_main_queue(), ^{
               NSError *error = nil;
               NSDictionary *allCarsDic = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingMutableContainers error:&error];
             
               if ([URL isEqualToString:@"http://cars.app.autohome.com.cn/dealer_v6.0.0/dealer/hotbrands-pm1.json"]) {
                   NSArray *array = allCarsDic[@"result"][@"list"];
                   NSLog(@"🐷🐷🐷🐷🐷🐷%ld", array.count);
                   if (array.count == 10) {
                        self.brand = [HotBrand modelWithDic:allCarsDic];
                   [self.tableView reloadData];
                   }
               } else if ([URL isEqualToString:@"http://adnewnc.app.autohome.com.cn/autov5.7.0/ad/infoad.ashx?appid=2&platform=1&version=6.2.0&networkid=0&adtype=1&provinceid=110000&lng=121.550888&lat=38.889660&pageindex=1&deviceid=d1ecb940123d620cb05a1b2b0a00da8bdd5e4fbe&idfa=981CD0F4-F1F0-4D0F-9C5E-58280F40E4B0&devicebrand=apple&devicemodel=iPhone&gps_city=210200&pageid=d1ecb940123d620cb05a1b2b0a00da8bdd5e4fbe1470913307169&isretry=0"]) {
                   NSArray *array = allCarsDic[@"result"][@"list"];
                   NSLog(@"🐷🐷🐷🐷🐷🐷%ld", array.count);
                   if (array.count == 3) {
                    self.extension = [Extension modelWithDic:allCarsDic];
                   [self.tableView reloadData];
                   }
               } else {
                   NSArray *array = allCarsDic[@"result"][@"brandlist"];
                   NSLog(@"🐷🐷🐷🐷🐷🐷%ld", array.count);
                   if (array.count > 10) {
                    self.allCars = [AllCars modelWithDic:allCarsDic];
                   [self.tableView reloadData];

                   }
               }
        });
    }];
    // 调用这个方法执行
    [dataTask resume];
}
#pragma mark - section
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
    return _allCars.result.brandlist.count + 4;
}
#pragma mark - row
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    if (section == 0) {
        return 1;
    } else if (section == 1) {
        return 1;
    } else if (section == 2) {
        return 1;
    } else if (section == 3) {
        return 1;
    } else {
        return _allCars.result.brandlist[section - 4].list.count;
    }
}
#pragma mark - cell
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    if (indexPath.section == 0) {
        TitleTableViewCell *cell =[tableView dequeueReusableCellWithIdentifier:kTitleTableViewCell];
        return cell;
    } else if (indexPath.section == 1) {
        HotBrandTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:kHotTableViewCell];
        cell.list = _brand.result.list;
        return cell;
    } else if (indexPath.section == 2){
        ExtensionTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:kExtensionTableViewCell];
        cell.extensionlist = _extension.result.list;
        return cell;
    } else if (indexPath.section == 3) {
        ChoseCarTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:kChoseTableViewCell];
        return cell;
    } else {
    AllCarsTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:kAllCarsTableViewCell];
    Brandlist *brandlist = _allCars.result.brandlist[indexPath.section - 4];
    List *list = brandlist.list[indexPath.row];
    cell.list = list;
    return cell;
    }
}
#pragma mark - 索引
- (NSArray<NSString *> *)sectionIndexTitlesForTableView:(UITableView *)tableView {
    NSMutableArray *array = [NSMutableArray array];
    for (Brandlist *brand in _allCars.result.brandlist) {
        [array addObject:brand.letter];
    }
    [array insertObject:@"⭐️" atIndex:0];
    [array insertObject:@"热" atIndex:1];
    [array insertObject:@"主" atIndex:2];
    [array insertObject:@"选" atIndex:3];
    return array;
}
#pragma mark - 头部标题
- (NSString *)tableView:(UITableView *)tableView titleForHeaderInSection:(NSInteger)section {
    NSString *str0 = @"热门品牌";
    NSString *str1 = @"主打车";
    NSString *str2 = @"选车神器";
    if (section == 0) {
        return nil;
    } else if (section == 1) {
        return str0;
    } else if (section == 2) {
        return str1;
    } else if (section == 3) {
        return  str2;
    } else {
    Brandlist *brand = _allCars.result.brandlist[section - 4];
    return brand.letter;
    }
}
#pragma mark - 设置分区头视图的高度
- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section {
    if (section == 0) {
        return 2;
    } else {
    return 30;
    }
}
#pragma mark - 设置row的高度
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
    if (indexPath.section == 0) {
        return 60;
    } else if (indexPath.section == 1){
    return 160;
    } else if (indexPath.section == 2){
        return 100;
    } else if (indexPath.section == 3) {
        return 80;
    } else {
        return 60;
    }
}
#pragma mark - 返回自定义的尾视图
- (UIView *)tableView:(UITableView *)tableView viewForFooterInSection:(NSInteger)section {
    UIView *view = [[UIView alloc] initWithFrame:CGRectMake(0, 0, CGRectGetWidth(self.view.bounds), 10)];
    view.backgroundColor = [UIColor colorWithWhite:0.95 alpha:0.5];
    return view;
}


- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}


@end
